<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handlerSearch" @reset="resetSearch" />

    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      ref="tableActionRef"
      :actionColumn="tableActionColumn"
      :scroll-x="860"
      bordered
    >
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>

    <!-- 修改密码的模态框 -->
    <n-modal
      v-model:show="resetShowModel"
      style="width: 300px"
      preset="card"
      title="密码重置"
      size="medium"
      :bordered="false"
    >
      <n-form
        ref="formRef"
        label-placement="left"
        size="large"
        :model="resetPwdFormParam"
        :rules="rules"
      >
        <n-form-item path="password">
          <n-input v-model:value="resetPwdFormParam.password" placeholder="请输入重置的密码">
            <template #prefix>
              <n-icon size="18" color="#808695">
                <LockClosedOutline />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item>
          <n-button type="primary" @click="handleSubmit" size="large" :loading="loading" block>
            重置
          </n-button>
        </n-form-item>
      </n-form>
    </n-modal>

    <!-- 修改角色的模态框 -->
    <n-modal
      v-model:show="resetRoleShowModel"
      style="width: 400px"
      preset="card"
      :title="`修改用户[${currentRow?.username}]的角色`"
      size="medium"
      :bordered="false"
    >
      <n-select v-model:value="roleId"
                label-field="roleName"
                value-field="id"
                :options="roleOptions" />
      <template #footer>
        <n-space justify="end">
          <n-button type="info" :loading="resetRoleLoading" @click="resetRoleHandler">修改</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import {useMessage, useDialog, NTag} from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getUserPage, updateStatus, resetUserPwd, updateRole } from '@/api/authority/user'
import { getRoleList } from "@/api/authority/role";
import { LockClosedOutline } from '@vicons/ionicons5';
import { useUserStore } from "@/store/modules/user";
import { NAvatar, NButton, NIcon } from "naive-ui";
import { useGlobSetting } from "@/hooks/setting";

const global = useGlobSetting()
const userStore = useUserStore()
const message = useMessage()
const dialog = useDialog()

const schemas: FormSchema[] = [
  {
    field: 'name',
    labelMessage: '注意哦, 不是用户昵称',
    component: 'NInput',
    label: '用户名',
    componentProps: {
      placeholder: '输入用户名',
      onInput: (e: any) => {
        searchForm.username = e;
      },
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '选择用户状态',
      options: [
        {
          label: '正常',
          value: '1',
        },
        {
          label: '禁用',
          value: '0',
        },
      ],
      onUpdateValue: (e: any) => {
        searchForm.status = e;
      },
    },
  },
  {
    field: 'range',
    component: 'NDatePicker',
    label: '创建时间',
    defaultValue: null,
    componentProps: {
      type: 'daterange',
      clearable: true,
      onUpdateFormattedValue: (e: any) => {
        searchForm.startTime = e[0]
        searchForm.endTime = e[1]
      },
    },
  },
];
// 按需搜索表单
const searchForm = reactive({
  username: null,
  status: null,
  startTime: null,
  endTime: null
})

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:3 2xl:4' },
  labelWidth: 85,
  schemas,
});

const handlerSearch = () => {
  reloadTable()
}

const resetSearch = () => {
  searchForm.username = searchForm.status = searchForm.startTime = searchForm.endTime = null
  reloadTable()
}

// 表格数据
const columns = [
  {
    title: '用户名',
    key: 'username',
    fixed: 'left',
    width: 80,
    align: 'center',
  },
  {
    title: '用户昵称',
    key: 'nickName',
    width: 100,
    align: 'center',
  },
  {
    title: '头像',
    key: 'avatar',
    width: 100,
    align: 'center',
    render(row) {
      return h(NAvatar, {
        size: 48,
        src: `${global.urlPrefix}${row.avatar}`,
      });
    },
  },
  {
    title: '联系电话',
    key: 'telephone',
    width: 100,
    align: 'center',
    render(row) {
      return h('span', {}, { default: () => row.telephone || "暂无绑定" });
    }
  },
  {
    title: '邮箱地址',
    key: 'email',
    width: 120,
    align: 'center',
    render(row) {
      return h('span', {}, { default: () => row.email || "暂无绑定" });
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 65,
    align: 'center',
    render(row) {
      return h(NTag, {
          type: row.status ? 'success' : 'warning',
          round: true,
          size: 'small'
        },
        { default: () => row.status ? '正常' : '禁用' }
      )
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 150,
    align: 'center',
  },
  {
    title: '最后登录时间',
    key: 'lastLoginTime',
    width: 150,
    align: 'center',
  },
];
const tableActionRef = ref();
const tableActionColumn = reactive({
  width: 120,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(row) {
    const show = row.id !== 1 && userStore.username !== row.username;
    // @ts-ignore
    return h(TableAction, {
      style: 'text',
      actions: [
        {
          label: row.status ? '禁用' : '启用',
          type: row.status ? 'warning' : 'success',
          ifShow: show,
          onClick: () => {
            dialog.warning({
              title: '警告',
              content: `${row.status ? '禁用' : '启用'}该用户账号?`,
              positiveText: '确定',
              negativeText: '取消',
              onPositiveClick: async () => {
                updateStatus(row.id).then(() => {
                  reloadTable()
                }).catch(e => dialog.destroyAll())
              },
              onNegativeClick: () => { }
            })
          }
        },
      ],
      dropDownActions: show ? [
        {
          label: '密码重置',
          key: 'reset',
          props: {
            onClick: () => {
              resetPwdFormParam.id = row.id
              resetPwdFormParam.password = ''
              resetShowModel.value = true
            }
          }
        },
        {
          label: '修改角色',
          key: 'role',
          props: {
            onClick: async () => {
              currentRow.value = row;
              roleId.value = row.role.id;
              roleOptions.value = await getRoleList();
              resetRoleShowModel.value = true;
            }
          }
        }
      ] : []
    });
  }
});


const loadDataTable = async (res) => {
  let params = {}
  if (searchForm.username) params['username'] = searchForm.username
  if (searchForm.status) params['status'] = searchForm.status
  if (searchForm.startTime) params['startTime'] = searchForm.startTime
  if (searchForm.endTime) params['endTime'] = searchForm.endTime
  const data = await getUserPage(
    { pageNumber: res.current, pageSize: res.size }, params
  );
  // total 指的是总共多少条数据
  const { current, size, total, records } = data;
  return {
    current,
    size,
    count: Math.ceil(total / size),
    records,
  };
};

function reloadTable() {
  tableActionRef.value.reload();
}

// 密码重置相关的东西
const loading = ref(false);
const resetShowModel = ref(false)
const formRef: any = ref(null);
const resetPwdFormParam = reactive({
  id: 0,
  password: ''
})
const rules = {
  password: { required: true, message: '请输入重置的密码', trigger: 'blur' }
};

const handleSubmit = (e) => {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const { id, password } = resetPwdFormParam;
      message.loading('重置中...');
      loading.value = true;
      try {
        await resetUserPwd(id, password)
      } finally {
        loading.value = false;
        resetShowModel.value = false;
      }
    } else {
      message.error('请填写完整信息');
    }
  });
};

// 角色修改相关
const resetRoleShowModel = ref(false);
const resetRoleLoading = ref(false)
const currentRow = ref()
const roleId = ref(1)
const roleOptions = ref([])

const resetRoleHandler = async () => {
  resetRoleLoading.value = true
  await updateRole(currentRow.value?.id, roleId.value)
    .finally(() => {
      resetRoleLoading.value = false
      resetRoleShowModel.value = false
    })
  reloadTable()
}
</script>

<style lang="less" scoped></style>
